from django.shortcuts import render
from django.http import HttpRequest,HttpResponse,HttpResponseRedirect,HttpResponseForbidden,HttpResponseBadRequest,JsonResponse,HttpResponseNotFound
# Create your views here.
from .models import Submission
from .tasksch import *
from .judger import *
import json
async def submit(request:HttpRequest):
    if request.method!="POST":
        return HttpResponseBadRequest("Invalid request method.")
    data=json.loads(request.body)
    prob=data.get("problem")
    author=data.get("submitter")
    body=data.get("body")
    type=data.get("type")
    sub=Submission()
    sub.body=body
    sub.problem=prob
    sub.submitter_id=int(author)
    sub.type=type
    await sub.asave()
    await add_task(sub.id)
    return HttpResponse(content="OK")

async def jregister(request:HttpRequest):
    if request.method!="POST":
        return HttpResponseBadRequest("Invalid request method")
    #try:
    # print("cap" in request.POST)
    # print(request.POST.get("cap"))
    data=json.loads(request.body)
    name=data.get("name")
    ip=data.get("addr")
    cap=data.get("cap")
    #except:
        #return HttpResponseBadRequest("Invalid request")
    f=await register(name,ip,cap)
    print(judgers)
    return HttpResponse(content="OK")
def heartbeat(request:HttpRequest):
    if request.method!="POST":
        return HttpResponseBadRequest("Invalid request method")
    data=json.loads(request.body)
    name=data.get("name")
    print("NM ",name)
    print(judgers)
    print("req ",request.get_host())
    if name not in judgers:
        return HttpResponseNotFound("Not existing judger")
    # if judgers[name].ip_addr!=request.get_host():
    #     return HttpResponseForbidden("Cannot request heartbeat from another machine")
    judgers[name].update()
    return HttpResponse(content="OK")

def mainpage(request:HttpRequest):
    return HttpResponse("Simple judge judgemgmt sys")

def complete(request:HttpRequest):
    if request.method!="POST":
        return HttpResponseBadRequest("Invalid request method")
    data=json.loads(request.body)
    name=data.get("name")
    print("COMPLETE ",name)
    details=data.get("detail")
    print("COMP det: ",details)
    stat=data.get("status")
    score=data.get("score")
    rid=data.get("submission_id")
    judgers[name].complete(rid)
    sub=Submission.objects.get(id=rid)
    sub.record=details
    sub.score=score
    sub.status=stat
    sub.save()
    return HttpResponse("OK")